package app.maker.user.impl;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import app.maker.entity.User;
import app.maker.error.UserException;
import app.maker.user.intf.IUser;

@Stateless(name = "daoUser")
public class UserImpl implements IUser {
	@PersistenceContext
	private EntityManager em;

	public void updateUser(User user) throws UserException {
		if (user != null) {
			em.merge(user);
		}
		else
			throw new UserException("Utilisateur inexistant!");

	}

	public void deleteUser(User user) throws UserException {
		//em.merge(user);
		
		if (user != null)
			em.remove(user);//em.find(User.class, user.getId()));
		else
			throw new UserException("Utilisateur inexistant!");

	}

	public User getUser(int id) throws UserException {
		if (id > 0)
			return em.find(User.class, id);
		else
			throw new UserException("Identifiant incorrecte!");
	}

	@SuppressWarnings("unchecked")
	public List<User> getAllUser() {
		return em.createNamedQuery("User.findAll").getResultList();
	}

	public User getUserByLogin(String login) throws UserException {
		User user = (User) em
				.createNamedQuery("User.findUserByLogin")
				.setParameter("param", login).getSingleResult();
		if (user != null)
			return user;
		else
			throw new UserException("User : " + login
					+ " inexistant !!!");
	}

}
